package br.megareleased.plugin.icefilms;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jd.http.Browser;
import jd.http.Request;
import jd.parser.html.Form;
import jd.parser.html.Form.MethodType;

import org.appwork.utils.net.httpserver.requests.HttpRequest;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.LinkRegexFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.ParserUtils;
import org.htmlparser.util.SimpleNodeIterator;

import br.megareleased.tools.WebBrowser;

public class IceFilmsPlugin {
	
	public static void main(String[] args) throws Exception {
//		 IceFilmsPlugin iceFilmsPlugin = new IceFilmsPlugin();
//		 Serie serie = iceFilmsPlugin.searchEpisodeList("the big bang theory");
//		 
//		 String url = serie.getSeasons().get(0).getEpisodes().get(0).getUrl();
//		 System.out.println("baixando " + url);
//		 
		 Browser br = new Browser();
		 String page = br.getPage("http://vds.icefilms.info//ip.php?v=116389&");
		 
		 NodeFilter nodeFilter = new NodeFilter() {
				@Override
				public boolean accept(Node arg0) {
					TagNameFilter filter = new TagNameFilter("iframe");
					return filter.accept(arg0);
				}
		};
			
		Node node = new Parser(page).extractAllNodesThatMatch(nodeFilter).elementAt(0);
		String mirrorUrl = node.getText().split(" ")[2].replaceFirst("src=\"/", "http://vds.icefilms.info/");
		System.out.println(mirrorUrl);
		
		page = br.getPage(mirrorUrl);
		br.getPage(mirrorUrl);
		
		Request request = br.createPostRequest("http://vds.icefilms.info/membersonly/components/com_iceplayer/video.phpAjaxResp.php", "id=266247");
		request.setCustomCharset("application/x-www-form-urlencoded");
		request.read();
		System.out.println(request.getHtmlCode());
		 
// 		 MegaUploadTest.teste(url);
	}

	private Browser br;
	private String iceFilmsBaseURL;
	
	public IceFilmsPlugin() {
		br = new Browser();
		iceFilmsBaseURL = "";
	}
	
	private Serie searchEpisodeList(String search) throws Exception {
		final Serie serie = new Serie();
		
		String iceFilmsURL = findIceFilmsEpisodeListURL(search);
		String page = getPage(iceFilmsURL);
		
		serie.setName(getSerieName(page));
		
		NodeFilter nodeFilter = new NodeFilter() {
			@Override
			public boolean accept(Node arg0) {
				TagNameFilter filter = new TagNameFilter("h4");
				return filter.accept(arg0);
			}
		};
		NodeList seassonNodeList = new Parser(page).extractAllNodesThatMatch(nodeFilter);
		
		SimpleNodeIterator seassonIterator = seassonNodeList.elements();
		while (seassonIterator.hasMoreNodes()) {
			Node nextNode = seassonIterator.nextNode();
			Season season = new Season(nextNode.toPlainTextString());
			serie.addSeason(season);
			
			nodeFilter = new NodeFilter() {
				@Override
				public boolean accept(Node arg0) {
					LinkRegexFilter filter = new LinkRegexFilter("ip.php?");
					if (filter.accept(arg0)
							&& arg0.toPlainTextString().startsWith(new String((serie.getSeasons().size() - 1) + ""))) {
						return true;
					}
					
					return false;
				}
			};
			
			NodeList episodeNodeList = new Parser(page).extractAllNodesThatMatch(nodeFilter);
			SimpleNodeIterator episodeIterator = episodeNodeList.elements();
			while (episodeIterator.hasMoreNodes()) {
				Node node = episodeIterator.nextNode();
				String episodeName = node.toPlainTextString();
				String url = node.getText().replaceAll("a href=", "");

				Episode episode = new Episode();
				episode.setName(episodeName);
				episode.setUrl(this.iceFilmsBaseURL + url);
				season.addEpisode(episode);
			}
		}
		
		return serie;
	}

	private String getPage(String iceFilmsURL) throws Exception {
		String page = null;
		
		try {
			this.iceFilmsBaseURL = "http://www.icefilms.info";
			page = br.getPage(iceFilmsURL);
		} catch (Exception e) {
			try {
				String[] url = iceFilmsURL.split("http://www");
				String mirror = "http://vds" + url[1];
				this.iceFilmsBaseURL = "http://vds.icefilms.info/";
				
				System.out.println("Tentando encontrar resultado no mirror " + mirror);
				page = br.getPage(mirror);
			} catch (Exception e2) {
				throw new Exception("Nenhum resultado encontrado.");	
			}
		}
		
		return page;
	}

	private String getSerieName(String page) throws ParserException {
		NodeFilter nodeFilter = new NodeFilter() {
			@Override
			public boolean accept(Node arg0) {
				TagNameFilter filter = new TagNameFilter("h1");
				return filter.accept(arg0);
			}
		};
		
		String serieName = new Parser(page).extractAllNodesThatMatch(nodeFilter).elementAt(0).toPlainTextString();
		return serieName;
	}

	private String findIceFilmsEpisodeListURL(String search) throws Exception {
		String googleSearch = "http://www.google.com/search?" +
				"q=" + search + "+%22-+Episode+List%22+" +
				"site%3Aicefilms.info&" +
				"hl=en";
		
		String page = getPage(googleSearch);
		
		Pattern pattern = Pattern.compile("http://www.icefilms.info(.+?) (?)");
		Matcher matcher = pattern.matcher(page);
		
		String iceFilmsURL = null;
		if (matcher.find()) {
			String result = matcher.group();
			iceFilmsURL = result.replaceAll("\"", "").trim();
		}
		
		return iceFilmsURL;
	}

}
